import axios, { type Method } from 'axios';
import { ElMessage } from 'element-plus';

const baseURL = import.meta.env.VITE_BASE_URL;
const instance = axios.create({ baseURL, timeout: 10000 });

instance.interceptors.request.use((config) => {
  return config;
});

instance.interceptors.response.use(
  (res) => {
    if (res.status !== 200) {
      ElMessage.error(res.statusText || '网络异常');
    }

    const { code, data, msg } = res.data;
    switch (code) {
      case 1:
        return data;
      default:
        msg && ~ElMessage.error(msg) && Promise.reject();
    }
  },
  (err) => Promise.reject(err)
);

const request = <T>(url: string, method: Method = 'GET', data?: object) => {
  return instance.request<T, T>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: data,
  });
};

export { baseURL, instance };

export default request;
